/**
 * 
 */
package co.fitstart.admin.handler.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.corp.CorpUser;
import com.demo2do.core.wechat.corp.handler.CorpMessageHandler;
import com.demo2do.core.wechat.corp.handler.CorpUserHandler;
import com.demo2do.core.wechat.corp.message.CorpMessage;
import com.demo2do.core.wechat.corp.message.CorpMessageStruct;
import com.demo2do.core.wechat.corp.message.CorpMessageStruct.CorpMessageStructBuilder;
import com.demo2do.core.wechat.corp.message.CorpMessageType;

import co.fitstart.admin.entity.message.MessageMapper;
import co.fitstart.admin.entity.message.Target;
import co.fitstart.admin.handler.TencentHandler;


/**
 * @author downpour
 *
 */
@Component("tencentHandler")
public class TencentHandlerImpl implements TencentHandler {
	
	@Value("#{ctx['corp.api.host']}")
	private String APIHOST;

    @Value("#{config['sms.mock']}")
    private boolean mock;

    
    private static final Logger logger = LoggerFactory.getLogger(TencentHandler.class);
    
    @Autowired
    private CorpMessageHandler corpMessageHandler;
    
    @Autowired
    private CorpUserHandler corpUserHandler;
    
    @Value("#{ctx['enterprise.agentid']}")
    private int agentid;

    /* (non-Javadoc)
     * @see co.fitstart.coach.handler.TencentHandler#sendMessage(java.lang.String, java.lang.String[])
     */
    public void sendMessage(String message, String... mobiles) {
        
        MessageMapper messageMapper = this.generateMessageMapper(message, mobiles);
        
        CorpMessageStruct corpMessageStruct = this.generateCorpMessageStruct(messageMapper);
        
        logger.trace("#sendMessage with CorpMessageStruct["+ corpMessageStruct.asJsonString() +"]");
        
        try {
            
            Result result = corpMessageHandler.send(corpMessageStruct);
            
            if(result.isValid()) {
                
                result.success().message("发送消息成功");
                
                logger.trace("#sendMessage: send corpMessage success!");
                
            } else {
                
                logger.error("#sendMessage: send corpMessage fail with Result [" + JsonUtils.toJsonString(result) + "]");
                
                result.fail().message("发送消息失败");
            }
            
            
        } catch (Exception e) {
            
            logger.error("#sendMessage: occur expection ["+ e + "]");
        }
        
    }
    
    /**
     * 
     * @param message
     * @param mobiles
     * @return
     */
    private MessageMapper generateMessageMapper(String message,  String... mobiles) {
        
        List<String> targetIds = Arrays.asList(mobiles);
        
        MessageMapper messageMapper = new MessageMapper(message, targetIds, agentid, Target.USER, CorpMessageType.TEXT);
        
        return messageMapper;
    }
    
    /**
     * 
     * @param messageMapper
     * @return
     */
    private CorpMessageStruct generateCorpMessageStruct(MessageMapper messageMapper) {
        
        CorpMessageStructBuilder builder = messageMapper.initBuilder();
        
        CorpMessage corpMessage = messageMapper.initCorpMessgae();
        
        CorpMessageStruct corpMessageStruct = builder.build(corpMessage);
        
        return corpMessageStruct;
    }
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.handler.TencentHandler#createUser(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
    public Result createUser(String userId, String mobile, String weixinid, String name) {
        
        CorpUser corpUser = this.generateCorpUser(userId, mobile, weixinid, name);
        
        Result result = this.onCreateUser(corpUser);
        
        if(!result.isValid()) {
            logger.error("TencentHandlerImpl#createUser() - create crop user failed with the foregoing reasons");
            result.fail().message("调用远程接口出错！");
        }
        
        return result;
    }
    
    /**
     * 
     * @param userid
     * @param mobile
     * @param name
     * @return
     */
    private CorpUser generateCorpUser(String userid, String mobile, String weixinxid, String name) {
        
        com.demo2do.core.wechat.corp.CorpUser.CorpUserBuilder builder = new com.demo2do.core.wechat.corp.CorpUser.CorpUserBuilder(userid, name);
        builder.department(new int[]{1});
        builder.mobile(mobile);
        builder.weixinid(weixinxid);
        
        CorpUser corpUser = builder.build();
        
        return corpUser;
    }
    
    private Result onCreateUser(CorpUser corpUser) {
        
        logger.trace("#onCreateUser with corpuser.userid["+ corpUser.getUserid() +"], corpUser.name[" + corpUser.getName() + "], corpUser.department["+ corpUser.getDepartment() +"], corpUser.mobile[" + corpUser.getMobile() + "]");
        
        Result result = new Result();
        
        if(corpUser.isAdequate()) {
            
            // Create corp user
            result = corpUserHandler.createUser(corpUser);
            
            if (result.isValid()) {
                
                // Get the new created corp user
                CorpUser user = corpUserHandler.getUser(corpUser.getUserid());
                
                if(user != null) {
                    
                    result.success()
                          .data("name", user.getName())   // FIXME let's put CorpUser here
                          .data("avatar", user.getAvatar())
                          .data("gender", user.getGender())
                          .message("添加企业号用户成功");
                    
                    logger.trace("#onCreate: create corpUser success!");
                    
                } else {
                    
                    logger.error("#onCreate: create corpUser fail, get user by openid failed!");
                    result.fail().message("获取企业号用户失败");
                }
            }
            
        } else {
            
            logger.error("#onCreate: create corpUser fail, corpUser is not adequate.");
            
            result.fail().message("corp user 参数不完整");
        }
        
        return result;
    }
    
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.handler.TencentHandler#sendCorpMessage(java.lang.String, java.lang.String)
     */
    public Result sendCorpMessage(String message, String mobile) {
    	
    	
        Result result = new Result();
        logger.info("mock [{}] message [{}] mobile [{}]",mock,message,mobile);
        try {
            if(mock) {
            	logger.info("发送成功");
                result.success().message("发送成功");
            } else {
                Map<String, String> parameters = new HashMap<>();
                parameters.put("message", message);
                parameters.put("mobile", mobile);
                
                String content = JsonUtils.toJsonString(parameters);
                
                Response response = Request.Post(APIHOST + "/v1/send-corp-message")
                                           .bodyString(content, ContentType.APPLICATION_JSON)
                                           .connectTimeout(100000)
                                           .socketTimeout(100000)
                                           .execute();
                
                String body = response.returnContent().asString(Consts.UTF_8);
                
                logger.trace("TencentHandler#sendCorpMessage() - Get response body [{}].", body);
                
                result = JSON.parseObject(body, Result.class);
            }
        } catch (Exception e) {
            logger.error("TencentHandler#sendCorpMessage() - Request wechat send corp message api euncouters exception: [{}]", e);
        }
        return result;
    }
    

}
